﻿#include "mainwindow.h"
#include "ui_form.h"
#include "QIcon"
#include "QFont"
#include <QTimer>
#include <QDateTime>
#include <QDebug>
#include <QLabel>
#include <QStringList>
#include <QSettings>
#include <QTextBrowser>
#include <QStringLiteral>
#include <QKeyEvent>
//#pragma execution_character_set("utf-8");
#include <QQuickWidget>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Form)
{
    ui->setupUi(this);
    PortScanTimer=new QTimer(parent);       //周期性扫描串口
    connect(PortScanTimer,SIGNAL(timeout()),this,SLOT(PortScan()));
    PortScanTimer->start(100);

    QStringList Baud,DataBit,ParityBit,StopBit;
    Baud<<"1200"<<"2400"<<"4800"<<"9600"<<"14400"<<"19200"<<"38400"<<"56000"<<"115200"<<"128000"<<"256000";
    DataBit<<"5"<<"6"<<"7"<<"8";
    ParityBit<<"无"<<"奇校验"<<"偶校验"<<"为0"<<"为1";
    StopBit<<"1"<<"1.5"<<"2";
    ui->baud->addItems(Baud);
    ui->baud->setCurrentIndex(8);
    ui->databit->addItems(DataBit);
    ui->databit->setCurrentIndex(3);
    ui->paritybit->addItems(ParityBit);
    ui->paritybit->setCurrentIndex(0);
    ui->stopbit->addItems(StopBit);
    ui->stopbit->setCurrentIndex(0);

//    QQuickWidget *mainMapBoxWidget = new QQuickWidget(this);
//    mainMapBoxWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
//    mainMapBoxWidget->setSource(QUrl::fromLocalFile("../test/chatUI.qml"));
//    mainMapBoxWidget->resize(100,100);
//    mainMapBoxWidget->show();

    setFocusPolicy(Qt::StrongFocus);
    ui->quickWidget->setSource(QUrl::fromLocalFile("../test/chatUI.qml"));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete PortScanTimer;
}

void MainWindow::PortScan()
{
//注册表方式查询COM端口
//    QSettings *reg = new QSettings("HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM",QSettings::NativeFormat);
//    QStringList comm = reg->childKeys();//childKeys
//    qDebug()<<comm;
//    if(comm.size() != ComNumSave)
//    {
//        ui->serialport->clear();
//        ui->serialport->addItems(comm);
//    }

//QSerialPortInfo方式查询COM端口
    QStringList ComName;
    static int ComSizeSave;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) //遍历并保存所有端口名称
    {
        ComName<<info.description()+" ("+info.portName()+")";
        if(ui->serialport->currentText() == (info.description()+" ("+info.portName()+")"))
        {
            PortNameSave=info.portName();
        }
    }
    if(ComName.size() != ComSizeSave)
    {
        ui->serialport->clear();
        ui->serialport->addItems(ComName);
    }
    ComSizeSave=ComName.size();
}

void MainWindow::on_OpenSerialButton_clicked()
{
    if(ui->OpenSerialButton->text() == tr("打开串口"))
    {
        Uart = new QSerialPort;
        PortScanTimer->stop();
        Uart->setPortName(PortNameSave);
        //打开串口
        Uart->open(QIODevice::ReadWrite);
        //修改按钮内容
        ui->OpenSerialButton->setText("关闭串口");
        //失能锁存所有输入框
        ui->serialport->setEnabled(false);
        ui->baud->setEnabled(false);
        ui->paritybit->setEnabled(false);
        ui->databit->setEnabled(false);
        ui->stopbit->setEnabled(false);
        //设置波特率
        Uart->setBaudRate(ui->baud->currentText().toInt());
        //设置校验位
        if(ui->paritybit->currentText()=="无")Uart->setParity(QSerialPort::NoParity);
        if(ui->paritybit->currentText()=="奇校验")Uart->setParity(QSerialPort::OddParity);
        if(ui->paritybit->currentText()=="偶校验")Uart->setParity(QSerialPort::EvenParity);
        if(ui->paritybit->currentText()=="为0")Uart->setParity(QSerialPort::SpaceParity);
        if(ui->paritybit->currentText()=="为1")Uart->setParity(QSerialPort::MarkParity);
        //设置数据位
        Uart->setDataBits(static_cast<QSerialPort::DataBits>(ui->databit->currentText().toInt()));
        //设置停止位
        switch(static_cast<int>(ui->stopbit->currentText().toDouble()*10))
        {
            case 10:
                Uart->setStopBits(QSerialPort::OneStop);
                break;
            case 15:
                Uart->setStopBits(QSerialPort::OneAndHalfStop);
                break;
            case 20:
                Uart->setStopBits(QSerialPort::TwoStop);
                break;
            default:break;
        }
        //设置流控制
        Uart->setFlowControl(QSerialPort::NoFlowControl);

        connect(Uart,SIGNAL(readyRead()),this,SLOT(ReadData()));
    }
    else
    {
        PortScanTimer->start(100);
        //关闭串口
        Uart->clear();
        Uart->close();
        //Uart->deleteLater();
        delete Uart;
        //修改按钮内容
        ui->OpenSerialButton->setText("打开串口");
        //失能锁存所有输入框
        ui->serialport->setEnabled(true);
        ui->baud->setEnabled(true);
        ui->paritybit->setEnabled(true);
        ui->databit->setEnabled(true);
        ui->stopbit->setEnabled(true);
    }
}

void MainWindow::on_SendButton_clicked()
{
   // Uart->waitForBytesWritten();
    Uart->write(ui->SendInput->toPlainText().toUtf8());
}

void MainWindow::ReadData()
{
    qDebug()<<"进入接收";
    QByteArray buf;
    buf = Uart->readAll();
    if(!buf.isEmpty())
    {
        QString str = ui->ReadInput->toPlainText();
        str+=tr(buf);
        ui->ReadInput->clear();
        ui->ReadInput->append(str);
    }
    buf.clear();
}

void MainWindow::keyPressEvent(QKeyEvent *ev)
{
    if ((ev->modifiers() == Qt::ControlModifier) && ev->key() == Qt::Key_A)
    {
        qDebug() << "press key up";
        MainWindow::on_SendButton_clicked();
        return;
    }
    if (ev->key() == Qt::Key_Down)
    {
        qDebug() << "press key down";
        return;
    }
    if (ev->key() == Qt::Key_Left)
    {
        qDebug() << "press key left";
        return;
    }
    if (ev->key() == Qt::Key_Right)
    {
        qDebug() << "press key right";
        return;
    }
}
